package com.lily.aidouzixun.activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.util.ArrayMap;
import android.util.SparseArray;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import com.lily.aidouzixun.MyApplication;
import com.lily.aidouzixun.R;
import com.lily.aidouzixun.bean.UserInfo;
import com.lily.aidouzixun.message.MessageDispatcher;
import com.lily.aidouzixun.message.MessageType;
import com.lily.aidouzixun.ui.TitleBar;
import com.lily.aidouzixun.util.HardWare;
import com.lily.aidouzixun.util.L;
import com.lily.aidouzixun.util.MyConfig;
import com.lily.aidouzixun.util.MyConstant;
import com.lily.aidouzixun.util.ProgressDialogUtil;
import com.lily.aidouzixun.util.T;
import com.lily.aidouzixun.util.Validator;
import com.lily.aidouzixun.util.MyConstant.*;
import java.lang.ref.WeakReference;

/**
 * 修改密码
 */
public class ModifyPasswordActivity extends Activity {
    private static final String TAG = "ModifyPasswordActivity";

    private TitleBar mTitleBar;
    private static ProgressDialog mProgressDialog; //网络请求时用的进度条
    private EditText etOldPwd;
    private EditText etNewPwd;
    private EditText etConfirmPwd;
    private Button bnSubmit;

    private String key = "";
    private Activity mActivity;
    private static Context mContext;
    private String backTitle;   //返回标题
    private static final String TITLE = "修改密码";
    private MyHandler myHandler;

    private String oldPwd;
    private String newPwd;
    private String confirmPwd;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.password_modify);
        init();
        findViews();
        setListeners();
    }

    /**
     * 初始化参数
     */
    private void init() {
        this.key += this.hashCode();
        mActivity = ModifyPasswordActivity.this;
        mContext = ModifyPasswordActivity.this;
        //得到返回标题
        Intent intent = getIntent();
        backTitle = intent.getStringExtra(MyConstant.IntentKey.BACK_TITLE);
        myHandler = new MyHandler(mActivity);
        mProgressDialog = ProgressDialogUtil.getProgressDialog(mContext);
    }
    /**
     * 找到控件
     */
    private void findViews() {
        //标题栏
        mTitleBar = (TitleBar) this.findViewById(R.id.mytitlebar);
        mTitleBar.setTitle(TITLE);
        mTitleBar.setLeftOperation(backTitle);
        mTitleBar.setCurActivity(mActivity);

        etOldPwd = (EditText) this.findViewById(R.id.et_password_old);
        etNewPwd = (EditText) this.findViewById(R.id.et_password_new);
        etConfirmPwd = (EditText) this.findViewById(R.id.et_password_confirm);
        bnSubmit = (Button) this.findViewById(R.id.bn_submit);
    }

    /**
     * 设置监听
     */
    private void setListeners() {
        //提交的监听
        bnSubmit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                oldPwd = etOldPwd.getText().toString().trim();
                newPwd = etNewPwd.getText().toString().trim();
                confirmPwd = etConfirmPwd.getText().toString().trim();
                if (!Validator.isEffective(oldPwd)) {
                    T.longToast(mContext, "原始密码不能为空");
                    return;
                }
                if (!Validator.isEffective(newPwd)) {
                    T.longToast(mContext, "原始新密码不能为空");
                    return;
                }
                if (!Validator.isEffective(confirmPwd)) {
                    T.longToast(mContext, "确定密码不能为空");
                    return;
                }
                if (!newPwd.equals(confirmPwd)) {
                    T.longToast(mContext, "两次密码不一致，请重新输入");
                    etConfirmPwd.setText("");
                    return;
                }
                //修改密码
                modifyPassword(oldPwd, newPwd);
            }
        });
    }

    /**
     *
     * @param oldPwd
     * @param newPwd
     */
    private void modifyPassword(String oldPwd, String newPwd) {
        if (!HardWare.isNetworkAvailable(mContext)) {
            T.shortToast(mContext, "请检查你的网络！");
            return ;
        }
        ArrayMap<String, Object> param = new ArrayMap<String, Object>();
        UserInfo userInfo = MyConfig.getUserInfo(mContext);
        if (userInfo == null) {
            T.shortToast(mContext, "请先登录！");
            return;
        }
        String username = userInfo.getUsername();
        if (!Validator.isEffective(username)) {
            T.shortToast(mContext, "请先登录！");
            return;
        }
        param.put(RequireParams.USER_NAME, username);
        param.put(RequireParams.PASSWORD, oldPwd);
        param.put(RequireParams.NEW_PASSWORD, newPwd);
        param.put(RequireParams.DATA_TYPE, DataType.MODIFY_PASSWORD);
        param.put(RequireParams.MAP_KEY, this.key + DataType.MODIFY_PASSWORD);
        param.put(RequireParams.CALL_BACK_HANDLER, myHandler);
        MessageDispatcher.sendMessage(MyApplication.getHandler(), MessageType.REQUIRE_DATA, param);
    }

    /**
     * 修改密码成功
     * 跳转到登录页面
     */
    private void modifyPasswordSuccess() {
        /*Intent intent = new Intent(mContext, LoginActivity.class);
        UserInfo userInfo = MyConfig.getUserInfo(mContext);
        if (userInfo != null) {
            intent.putExtra(IntentKey.USER_NAME, userInfo.getUsername());
        }*/
        //设置userinfo为空
        MyConfig.setUserInfo(mContext, null);
        this.setResult(IntentForResultCODE.MODIFY_PASSWORD_RESULTCODE, null);
        this.finish();
    }
    /**
     * 自定义的Handler
     */
    static class MyHandler extends Handler {
        WeakReference<Activity> mActivityReference;

        /**
         * 构造方法，传递Activity对象，防止内存泄露
         * @param mActivity
         */
        MyHandler(Activity mActivity) {
            mActivityReference = new WeakReference<Activity>(mActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            try {
                final ModifyPasswordActivity activity = (ModifyPasswordActivity) mActivityReference.get();
                if(activity !=  null) {
                    super.handleMessage(msg);
                    switch (msg.what) {
                        case MessageType.SHOW_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.setMessage("正在更改密码...");
                                mProgressDialog.show();
                            }
                            break;
                        case MessageType.CLOSE_DIALOG:  //关闭对话框
                            if (mProgressDialog != null) {
                                mProgressDialog.dismiss();
                            }
                            break;
                        case MessageType.REQUIRE_DATA_FINISHED: //请求数据完成
                            if (msg.arg1 == DataType.MODIFY_PASSWORD) { //修改密码  errno:0-密码修改成功；1-密码修改失败；
                                SparseArray<Object> result = (SparseArray<Object>) msg.obj;
                                String errno = (String) result.get(0);
                                if ("0".equals(errno)) {    //修改成功
                                    activity.modifyPasswordSuccess();
                                } else if("1".equals(errno)){   //修改失败
                                    T.shortToast(mContext, "旧密码错误，请重新输入！");
                                } else {    //其他原因
                                    T.shortToast(mContext, "服务器正忙，稍后再试！");
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
            } catch (Exception e) {
                L.e(TAG, "handleMessage Exception!");
            }
        }
    }
}
